import { promisic } from './utils.js'
import { Throwable } from "../err_handle/throwable.js"

const openSetting = function({
	scope,
	desc
}) {
	return promisic(uni["showModal"])({
			content: desc,
			cancelText: "任性不去",
			confirmText: "去设置",
		})
		.catch((error) => {
			return Promise.reject(new Throwable(10000, "authorize:fail:系统错误"))
		})
		.then((res) => {
			if (res && res.confirm) {
				return promisic(uni["openSetting"])()
					.catch((error) => {
						return Promise.reject(new Throwable(10000, "authorize:fail:系统错误"))
					})
					.then((res) => {
						let authSetting = res.authSetting || {}
						if (authSetting[scope]) {
							return Promise.resolve()
						} else {
							return openSetting({
								scope,
								desc
							})
						}
					})
			}
			return Promise.reject(new Throwable(10000, "authorize:fail:auth canceled"))
		})
}

export const authorize = function({
	scope = "",
	desc = ""
}) {
	if (!scope) {
		return Promise.reject(new Throwable(10000, "authorize:fail:scope is undefine"))
	}
	if (!desc) {
		return Promise.reject(new Throwable(10000, "authorize:fail:desc is undefine"))
	}

	return promisic(uni["authorize"])({
			scope
		})
		.catch((error) => {
			return promisic(uni["getSetting"])()
				.catch((error) => {
					return Promise.reject(new Throwable(10000, "authorize:fail:系统错误"))
				})
				.then((res) => {
					let authSetting = res.authSetting || {}
					let keys = Object.keys(authSetting)
					if (keys.indexOf(scope) != -1) {
						if (authSetting[scope]) {
							return Promise.reject(new Throwable(10000, "authorize:fail:系统错误"))
						} else {
							return openSetting({
								scope,
								desc
							})
						}
					} else {
						return Promise.reject(new Throwable(10000, "authorize:fail:auth canceled"))
					}
				})
		})
}
